import 'package:flutter/material.dart';
import 'package:jd_shop/net/MallmsService.dart';
import 'package:jd_shop/routers/AppRoutes.dart';

import '../../model/ClassLeft.dart';
import '../../model/ClassRight.dart';
import '../../model/GdsCats.dart';
import '../../services/ScreenAdaper.dart';

class ClassPage extends StatefulWidget {
  const ClassPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _ClassPageState();
  }
}

class _ClassPageState extends State<ClassPage>
    with AutomaticKeepAliveClientMixin {
  final TextEditingController _controller = TextEditingController();
  List<ClassLeft> classLeft = [];
  List<ClassRight> classRight = [];
  var catParentId = 0;

  @override
  void initState() {
    super.initState();
    _getClassLeft();
  }

  _getClassLeft() async {
    var classLeft = await MallmsService.getClassList();
    this.classLeft = classLeft!;
    _getLeftClassWidget();
    if (classLeft.isNotEmpty) {
      catParentId = classLeft[0].gdsCats![0].catId!;
      _getClassRight();
    }
    setState(() {});
  }

  _getClassRight() async {
    var classRight = await MallmsService.getRightClassList(catParentId);
    this.classRight = classRight!;
    _itemGoodsWidgetList = [];
    classRight.forEach((element) {
      element.gdsCats?.forEach((element) {
        _itemGoodsWidgetList.add(_itemGoodsWidget(element));
      });
    });

    _getRightClassWidget();
    setState(() {});
  }

  var selectLeftPosition = 0;

  _getLeftClassWidget() {
    return SizedBox(
      width: 80,
      height: double.infinity -
          ScreenAdapter.height(40) -
          ScreenAdapter.getStatusBarHeight(),
      child: classLeft.isNotEmpty
          ? ListView.builder(
              itemCount: classLeft[0].gdsCats?.length,
              itemBuilder: (context, index) {
                return InkWell(
                  onTap: () {
                    setState(() {
                      selectLeftPosition = index;
                      catParentId = classLeft[0].gdsCats![index].catId!;
                      _getClassRight();
                    });
                  },
                  child: Container(
                    height: (ScreenAdapter.getScreenHeight() -
                            ScreenAdapter.height(40) -
                            ScreenAdapter.getStatusBarHeight()) /
                        (classLeft[0].gdsCats!.length + 1),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: index == selectLeftPosition
                          ? Colors.grey.shade300
                          : Colors.white,
                    ),
                    child: Text("${classLeft[0].gdsCats?[index].catName}"),
                  ),
                );
              })
          : const Center(child: Text("加载中...")),
    );
  }

  _getRightClassWidget() {
    return Container(
      margin: EdgeInsets.only(left: ScreenAdapter.height(5)),
      padding: EdgeInsets.only(left: ScreenAdapter.height(5)),
      height: double.infinity,
      child: classLeft.isNotEmpty
          ? ListView.builder(
              itemCount: classRight.length,
              itemBuilder: (context, index) {
                return Container(
                  margin: EdgeInsets.only(bottom: ScreenAdapter.height(10)),
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.only(bottom: ScreenAdapter.height(10)),
                  decoration: const BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    children: [
                      Container(
                        alignment: Alignment.centerLeft,
                        height: ScreenAdapter.height(40),
                        padding:
                            EdgeInsets.only(left: ScreenAdapter.height(10)),
                        decoration: const BoxDecoration(
                            borderRadius:
                                BorderRadius.all(Radius.circular(10))),
                        child: Text("${classRight[index].secordCatName}"),
                      ),
                      _rightGoodsListWidget()
                    ],
                  ),
                );
              })
          : const Center(child: Text("加载中...")),
    );
  }

  List<Widget> _itemGoodsWidgetList = [];

  _rightGoodsListWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      margin: const EdgeInsets.only(left: 10, right: 10),
      child: Wrap(spacing: 10, runSpacing: 10, children: _itemGoodsWidgetList),
    );
  }

  Widget _itemGoodsWidget(GdsCats goodsInfoList) {
    return Container(
        width: (ScreenAdapter.getScreenWidth() - 140) / 3,
        child: InkWell(
            onTap: () {
              Navigator.pushNamed(context, AppRoutes.SEARCH_GOODS,
                  arguments: {"catId": goodsInfoList.catId});
            },
            child: Column(
              children: [
                Image.network(
                  goodsInfoList.catPic!,
                  width: ScreenAdapter.height(40),
                  height: ScreenAdapter.height(40),
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) => Image.asset(
                      "images/error_image.webp",
                      width: ScreenAdapter.height(40),
                      height: ScreenAdapter.height(40),
                      fit: BoxFit.cover),
                ),
                Text("${goodsInfoList.catName}")
              ],
            )));
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);
    return MediaQuery.removePadding(
        removeTop: true,
        context: context,
        child: Container(
          height: double.infinity,
          width: double.infinity,
          child: Stack(children: [
            Container(
                color: Colors.blue,
                height: ScreenAdapter.height(40) +
                    ScreenAdapter.getStatusBarHeight(),
                padding: EdgeInsets.only(
                    top: ScreenAdapter.getStatusBarHeight(),
                    left: 30,
                    right: 30),
                child: InkWell(
                  onTap: () {
                    Navigator.pushNamed(context, AppRoutes.SEARCH_GOODS,
                        arguments: {});
                  },
                  child: Row(
                    children: [
                      //有圆角白色底的 搜索框
                      Expanded(
                          child: Container(
                        height: ScreenAdapter.height(30),
                        margin:
                            EdgeInsets.only(right: ScreenAdapter.height(10)),
                        child: const TextField(
                          decoration: InputDecoration(
                              border: OutlineInputBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(10)),
                                  borderSide: BorderSide(
                                      color: Colors.white, width: 1)),
                              filled: true,
                              fillColor: Colors.white,
                              hintText: "请输入搜索内容",
                              //居中
                              contentPadding:
                                  EdgeInsets.only(left: 10, right: 10),
                              //禁止输入
                              enabled: false,
                              hintStyle: TextStyle(color: Colors.grey)),
                          style: TextStyle(
                            fontSize: 10,
                          ),
                        ),
                      )),
                      Icon(Icons.search, color: Colors.white),
                    ],
                  ),
                )),
            Positioned(
              top:
                  ScreenAdapter.height(40) + ScreenAdapter.getStatusBarHeight(),
              left: 0,
              right: 0,
              bottom: 0,
              child: Row(children: [
                _getLeftClassWidget(),
                Expanded(child: _getRightClassWidget())
              ]),
            )
          ]),
        ));
  }

  @override
  bool get wantKeepAlive => true;
}
